package com.wyl.login.activity

import androidx.databinding.ObservableBoolean
import androidx.databinding.ObservableField
import androidx.lifecycle.MutableLiveData
import com.lzg.extend.BaseResponse
import com.lzg.extend.JsonConvert
import com.lzg.extend.toDisposables
import com.lzy.okgo.OkGo
import com.lzy.okgo.callback.StringCallback
import com.lzy.okgo.model.Response
import com.lzy.okrx2.adapter.ObservableBody
import com.umeng.socialize.bean.SHARE_MEDIA
import com.wyl.base.*
import com.wyl.base.bean.UserData
import com.wyl.libbase.base.BaseViewModel
import com.wyl.libbase.utils.Validator
import com.wyl.libbase.extend.encode
import com.wyl.login.R
import com.wyl.login.context
import org.json.JSONObject

class LoginViewModel : BaseViewModel() {

    val username: ObservableField<String> = ObservableField()
    val code: ObservableField<String>  by lazy { ObservableField<String>() }
    val pwd: ObservableField<String> = ObservableField()
    val confrimPwd: ObservableField<String> by lazy { ObservableField<String>() }
    val agreement = ObservableBoolean(true)
    val codeSuccess: MutableLiveData<String> by lazy { MutableLiveData<String>() }

    val bindPhone: MutableLiveData<String> = MutableLiveData()

    // 三方登录
    var qqid = ""
    var wxid = ""
    var avatar = ""
    var nickname = ""
    var platform = SHARE_MEDIA.WEIXIN

    fun getMessageCode() {
        if (username.get().isNullOrEmpty()) {
            error.value = context.getString(R.string.login_empty_invalid_user_name)
            return
        }
        if (!Validator.isMobile(username.get())) {
            error.value = context.getString(R.string.login_empty_invalid_user_name)
            return
        }

        OkGo.post<String>(COMMON_GETCODE)
            .params("phone", username.get())
            .execute(object : StringCallback() {
                override fun onSuccess(response: Response<String>) {
                    val obj = JSONObject(response.body())
                    if (obj.optInt("msg") == 0) {
                        //成功
                        codeSuccess.value = "获取验证码成功"
                        ACacheHelper.putCode(obj.optString("code"))
                    } else
                        error.value = "获取验证码失败"
                }

                override fun onError(response: Response<String>) {
                    error.value = "请求失败"
                }

                override fun onFinish() {
                    loading.value = false
                }
            })
    }

    fun register() {
        if (!agreement.get()) {
            error.value = context.getString(R.string.login_no_agreement)
            return
        }
        if (username.get().isNullOrEmpty()) {
            error.value = context.getString(R.string.login_empty_invalid_user_name)
            return
        }
        if (!Validator.isMobile(username.get())) {
            error.value = context.getString(R.string.login_error_invalid_user_name)
            return
        }
        if (code.get().isNullOrEmpty()) {
            error.value = context.getString(R.string.login_empty_invalid_code)
            return
        }
        if (ACacheHelper.getMsgCode() != code.get()) {
            error.value = context.getString(R.string.login_error_invalid_code)
            return
        }
        if (pwd.get().isNullOrEmpty()) {
            error.value = context.getString(R.string.login_empty_invalid_password)
            return
        }
//        if (pwd.get()!!.length < 6) {
//            error.value = context.getString(R.string.login_error_invalid_password)
//            return
//        }
        if (pwd.get() != confrimPwd.get()) {
            error.value = context.getString(R.string.login_error_invalid_password2)
            return
        }

        OkGo.post<BaseResponse<UserData>>(LOGIN_REGISTER)
            .params("phone", username.get())
            .params("password", pwd.get().toString().encode())
            .converter(object : JsonConvert<BaseResponse<UserData>>() {})
            .adapt(ObservableBody<BaseResponse<UserData>>())
            .doOnSubscribe { loading.value = true }
            .doFinally { loading.value = false }
            .subscribe(
                {
                    success.value = context.getString(R.string.login_register_success)
                    ACacheHelper.login(it.data)
                }, this::onError
            ).toDisposables(disposables)
    }

    fun login() {
        if (!agreement.get()) {
            error.value = context.getString(R.string.login_no_agreement)
            return
        }
        if (username.get().isNullOrEmpty()) {
            error.value = context.getString(R.string.login_empty_invalid_user_name)
            return
        }
        if (!Validator.isMobile(username.get())) {
            error.value = context.getString(R.string.login_error_invalid_user_name)
            return
        }
        if (pwd.get().isNullOrEmpty()) {
            error.value = context.getString(R.string.login_empty_invalid_password)
            return
        }

        OkGo.post<BaseResponse<UserData>>(LOGIN_LOGIN)
            .params("phone", username.get())
            .params("password", pwd.get().toString().encode())
            .converter(object : JsonConvert<BaseResponse<UserData>>() {})
            .adapt(ObservableBody<BaseResponse<UserData>>())
            .doOnSubscribe { loading.value = true }
            .doFinally { loading.value = false }
            .subscribe(
                {
                    if (it.code == 0) {
                        success.value = it.msg
                        ACacheHelper.login(it.data)
                    } else {
                        toast.value = it.msg
                    }
                }, this::onError
            ).toDisposables(disposables)
    }

    fun loginThree() {
        val account = when (platform) {
            SHARE_MEDIA.WEIXIN -> wxid
            SHARE_MEDIA.QQ -> qqid
            else -> ""
        }
        OkGo.post<BaseResponse<UserData>>(LOGIN_LOGIN_THREE)
            .params("account", account)
            .converter(object : JsonConvert<BaseResponse<UserData>>() {})
            .adapt(ObservableBody<BaseResponse<UserData>>())
            .doOnSubscribe { loading.value = true }
            .doFinally { loading.value = false }
            .subscribe(
                {
                    if (it.code == 0) {
                        success.value = it.msg
                        ACacheHelper.login(it.data)
                    } else {
                        bindPhone.value = "无账号"
                    }
                }, this::onError
            ).toDisposables(disposables)
    }


    fun forget() {
        if (username.get().isNullOrEmpty()) {
            error.value = context.getString(R.string.login_empty_invalid_user_name)
            return
        }
        if (!Validator.isMobile(username.get())) {
            error.value = context.getString(R.string.login_error_invalid_user_name)
            return
        }
        if (code.get().isNullOrEmpty()) {
            error.value = context.getString(R.string.login_empty_invalid_code)
            return
        }
        if (ACacheHelper.getMsgCode() != code.get()) {
            error.value = context.getString(R.string.login_error_invalid_code)
            return
        }
        if (pwd.get().isNullOrEmpty()) {
            error.value = context.getString(R.string.login_empty_invalid_password)
            return
        }

        OkGo.post<BaseResponse<UserData>>(LOGIN_FORGET)
            .params("phone", username.get())
            .params("password", pwd.get().toString().encode())
            .converter(object : JsonConvert<BaseResponse<UserData>>() {})
            .adapt(ObservableBody<BaseResponse<UserData>>())
            .doOnSubscribe { loading.value = true }
            .doFinally { loading.value = false }
            .subscribe({
                success.value = it.msg
            }, {
                onError(it)
            }).toDisposables(disposables)
    }

    fun bindingPhone(phone: String) {
        val type = when (platform) {
            SHARE_MEDIA.WEIXIN -> "weixin" to wxid
            SHARE_MEDIA.QQ -> "qq" to qqid
            else -> "" to ""
        }
        OkGo.post<BaseResponse<UserData>>(LOGIN_REGISTER)
            .params("phone", phone)
            .params(mapOf(type))
            .params("name", nickname)
            .params("avatar", avatar)
            .converter(object : JsonConvert<BaseResponse<UserData>>() {})
            .adapt(ObservableBody<BaseResponse<UserData>>())
            .doOnSubscribe { loading.value = true }
            .doFinally { loading.value = false }
            .subscribe(
                {
                    if (it.code == 0) {
                        success.value = context.getString(R.string.login_register_success)
                        ACacheHelper.login(it.data)
                    } else {
                        toast.value = it.msg
                    }
                }, this::onError
            ).toDisposables(disposables)
    }

}
